package com.tedu.sp11.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.tedu.web.util.JsonResult;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
@Component
public class AccessFilter extends ZuulFilter {
    //定义过滤器类型 : pre post routing error
    @Override
    public String filterType() {
        //return "pre";
        return FilterConstants.PRE_TYPE;
    }

    //过滤器插入位置
    @Override
    public int filterOrder() {
        return 6;
    }

    //对用户请求进行判断，是否要执行过滤代码
    @Override
    public boolean shouldFilter() {
        /*
        只对item-service调用进行过滤
         */
        //获得调用的服务id
        RequestContext context = RequestContext.getCurrentContext();
        String serviceId = (String)context.get(FilterConstants.SERVICE_ID_KEY);
        return "item-service".equalsIgnoreCase(serviceId);
    }

    //过滤代码
    @Override
    public Object run() throws ZuulException {

        //获取request对象
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();

        //接收token参数
        String token = request.getParameter("token");

        //如果没有token，阻止访问
        if (!StringUtils.hasLength(token)){
            //阻止继续访问
            context.setSendZuulResponse(false);
            String json = JsonResult.err().code(JsonResult.NOT_LOGIN).msg("没有登录").toString();
            context.addZuulResponseHeader("Content-Type","application/json;charset=UTF-8" );
            context.setResponseBody(json);
        }
        return null;//返回值没有作用
    }
}
